package com.szyt.basicframe.util;

import cn.hutool.core.lang.Snowflake;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@ConfigurationProperties(prefix="snowflake")
public class IdUtil {
    //workerId和datacenterId分别占5个比特，共同组成机器id
    //注意分布式环境下workerId和datacenterId要取不同的值
    private static volatile Snowflake snowflake;
    private Long workerId;
    private Long datacenterId;

    public void setWorkerId(Long workerId) {
        this.workerId = workerId;
    }

    public void setDatacenterId(Long datacenterId) {
        this.datacenterId = datacenterId;
    }

    @PostConstruct
    private void init() {
        if (workerId == null || datacenterId == null) {
            throw new IllegalStateException("未初始化参数，生成id失败");
        }
        snowflake = cn.hutool.core.util.IdUtil.getSnowflake(workerId, datacenterId);
    }


    public static long getId() {
        if (snowflake == null) throw new IllegalStateException("未初始化生成器，生成id失败");
        return snowflake.nextId();
    }
}
